package com.tude.egarticle3.controller;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.tude.egarticle3.base.response.CodeMsg;
import com.tude.egarticle3.base.response.JsonResult;
import com.tude.egarticle3.mapper.UserMapper;
import com.tude.egarticle3.pojo.dto.UserArticleParam;
import com.tude.egarticle3.pojo.dto.UserLoginParam;
import com.tude.egarticle3.pojo.entity.Article;
import com.tude.egarticle3.pojo.vo.ArticleVO;
import com.tude.egarticle3.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;

@Api(tags = "测试模块")
@Validated
@Slf4j
@RestController
@RequestMapping("/v1/user/")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @ApiOperation("用户登录")
    @ApiOperationSupport(order = 1)
    @PostMapping("login")
    public JsonResult login(@RequestBody UserLoginParam userLoginParam, @ApiIgnore HttpSession session) {
        log.info("userLoginParam:"+userLoginParam);
        UserVO userVO = userMapper.selectByUAP(userLoginParam);
        if (userVO == null) {
            return new JsonResult(CodeMsg.USERNAME_PASSWORD_ERROR);
        }
        session.setAttribute("user", userVO);
        return JsonResult.success();
    }

    @ApiOperation("发表文章")
    @ApiOperationSupport(order = 2)
    @PostMapping("article")
    public JsonResult article(@RequestBody @Validated UserArticleParam userArticleParam,
                              @ApiIgnore HttpSession session) {
        UserVO userVO = (UserVO)session.getAttribute("user");
        if (userVO == null) {
            return new JsonResult(CodeMsg.NOT_LOGIN);
        }
        Article article = new Article();
        BeanUtils.copyProperties(userArticleParam, article);
        article.setUserId(userVO.getId());
        userMapper.insertArticle(article);

        return JsonResult.success();
    }

    @ApiOperation("查询指定文章内容")
    @ApiOperationSupport(order = 3)
    @GetMapping("selectByArticleId")
    public JsonResult selectByArticleId(@Range(min = 1, max = 100, message = "文章ID要求在1-100之间") @RequestParam Long id){
        ArticleVO articleVO = userMapper.selectByArticleId(id);
        return JsonResult.success(articleVO);
    }
}
